class ApplicationController < ActionController::Base

  before_filter :application_init
  
  protect_from_forgery

  helper_method :current_user, :current_user_session

  helper :all
  
  def title(title_text)
    content_for :title, title_text.to_s
  end

  def content_for(name, content)
    @_content_for ||= {}
    if @_content_for[name].respond_to?(:<<)
      @_content_for[name] << content
    else
      @_content_for[name] = content
    end
  end

  if config.consider_all_requests_local
    rescue_from Exceptions::TemplateNotFound,        :with => :render_error
    rescue_from Exception,                           :with => :render_error
    rescue_from ActiveRecord::RecordNotFound,        :with => :render_page_not_found
    rescue_from ActionController::UnknownController, :with => :render_not_found
    rescue_from ActionController::UnknownAction,     :with => :render_not_found
  end

  def render_not_found(message = nil)
    @message = message

    title "Požadovaná stránka nebyla nalezena"

    render :template => "errors/not_found"
  end

  def render_error(exception)
    @exception = exception
    
    title "Na serveru se vyskytla chyba E500"

    render :template => "errors/server_error"
  end

  def permission_denied
    if logged_in?
      flash[:error] = "Nemáte dostatečná práva pro přístup do této sekce."
      session[:return_to] = nil
      redirect_to :back rescue redirect_to('/')
    else
      flash[:error] = "Přihlašte se prosím."
      store_location
      redirect_to login_path
    end
  end

  def application_init
    GlobalObserver.current_user = current_user
  end
  
  protected
  def logged_in?
    return current_user ? true : false
  end

  def is_post?
    return request.post? ? true : false
  end

  def store_location
    disallowed_urls = [login_url, logout_url]
    disallowed_urls.map!{ |url| url[/\/\w+$/] }
    
    unless disallowed_urls.include?(request.fullpath)
      session[:return_to] = request.fullpath
    end
  end

  def redirect_back_or_default(default)
    redirect_to(session[:return_to] || default)
    session[:return_to] = nil
  end

  def require_user
    unless logged_in?
      store_location
      render :template => "errors/require_user"
    end
  end

  def require_no_user
    if logged_in?
      store_location
      render :template => "errors/require_no_user"
    end
  end

  def current_user
    return @current_user if defined?(@current_user)
    @current_user = current_user_session && current_user_session.user
  end

  def current_user_session
    return @current_user_session if defined?(@current_user_session)
    @current_user_session = UserSession.find
  end
  
  private
  def undo_link(object)
    unless object.versions.blank?
      view_context.link_to("Vzít zpět.", revert_version_path(object.versions.scoped.last), :method => :post)
    end
  end
end
